package com.china08.yxyapi.api.manage.sch.platform.website.section;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.entity.db.sws.SwsSection;
import com.china08.yxyapi.entity.mg.sws.SwsArticle;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.SwsSectionRepository;
import com.china08.yxyapi.repository.mg.SwsArticleRepository;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController("SectionMoveController")
public class SectionMoveController {

    @Autowired
    SwsSectionRepository swsSectionRepository;

    @Autowired
    SwsArticleRepository SwsArticleRepository;

    @ApiOperation("移动栏目")
    @RequestMapping(value = "/api_yw/manage/sch/platform/website/section/move", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {

        String pid = reqModel.pid;
        String sectionId = reqModel.sectionId;

        // 移动栏目
        SwsSection swsSection = swsSectionRepository.findById(sectionId);
        Assert.isTrue(null != swsSection, "不存在当前栏目");
        swsSection.setPid(pid);
        swsSectionRepository.save(swsSection);

        // 移动文章
        List<SwsArticle> swsArticles = SwsArticleRepository.findBySection2Id(sectionId);
        for (SwsArticle swsArticle : swsArticles) {
            swsArticle.setSection1Id(pid);
            SwsArticleRepository.save(swsArticle);
        }
        return true;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String sectionId;
        public String pid;

        @Override
        public void autoCheck() {
            Assert.isTrue(StringUtils.isNotBlank(pid), "一级栏目未选定");
            Assert.isTrue(StringUtils.isNotBlank(sectionId), "二级栏目未选定");
        }
    }

    protected static class RespModel extends YxyApiRespModel {
    }
}
